const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      nickname: "",
      id: "",
      avatarUrl: "",
    },
    deviceCount: 0,
    neteaseBound: false,
    listeningHours: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取用户信息
    this.getUserInfo();
    // 获取设备数据
    this.getDeviceInfo();
    // 获取网易云账号绑定状态
    this.getNeteaseAccountStatus();
    // 获取听歌时长
    this.getListeningDuration();
  },

  /**
   * 获取用户信息
   */
  getUserInfo: function () {
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo) {
      this.setData({
        userInfo: {
          nickname: userInfo.nickname || userInfo.username || "用户",
          id: userInfo.userId || "",
          avatarUrl: userInfo.avatarUrl || "",
        },
      });
    } else {
      // 如果本地没有用户信息，从服务器获取
      this.fetchUserInfoFromServer();
    }
  },

  /**
   * 从服务器获取用户信息
   */
  fetchUserInfoFromServer: function () {
    // 检查是否有令牌
    const token = wx.getStorageSync("token");
    if (!token) {
      // 没有令牌，需要登录
      wx.redirectTo({
        url: "/pages/login/login",
      });
      return;
    }

    wx.request({
      url: `${app.globalData.apiBaseUrl}/user/info`,
      method: "GET",
      header: {
        Authorization: `Bearer ${token}`,
      },
      success: (res) => {
        if (res.data && res.data.code === 0) {
          const userData = res.data.data;
          // 保存到本地存储
          wx.setStorageSync("userInfo", userData);
          // 更新页面数据
          this.setData({
            userInfo: {
              nickname: userData.nickname || userData.username || "用户",
              id: userData.userId || "",
              avatarUrl: userData.avatarUrl || "",
            },
          });
        } else {
          wx.showToast({
            title: "获取用户信息失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.error("获取用户信息失败", err);
        wx.showToast({
          title: "网络错误，请稍后再试",
          icon: "none",
        });
      },
    });
  },

  /**
   * 获取设备信息
   */
  getDeviceInfo: function () {
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo && userInfo.userId) {
      const app = getApp();
      wx.request({
        url: `${app.globalData.deviceApiBaseUrl}/api/v1/get_devices`,
        method: "GET",
        data: {
          user_id: userInfo.userId,
        },
        success: (res) => {
          if (res.data && res.data.code === 0 && res.data.devices) {
            this.setData({
              deviceCount: res.data.devices.length,
            });
          }
        },
        fail: (err) => {
          console.error("获取设备数量失败", err);
        },
      });
    }
  },

  /**
   * 获取网易云账号绑定状态
   */
  getNeteaseAccountStatus: function () {
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo && userInfo.userId) {
      wx.request({
        url: `${app.globalData.apiBaseUrl}/api/v1/check_netease_binding`,
        method: "GET",
        data: {
          user_id: userInfo.userId,
        },
        success: (res) => {
          if (res.data && res.data.code === 0) {
            this.setData({
              neteaseBound: res.data.is_bound || false,
            });
          }
        },
        fail: (err) => {
          console.error("获取网易云账号绑定状态失败", err);
          this.setData({
            neteaseBound: false,
          });
        },
      });
    }
  },

  /**
   * 获取听歌时长
   */
  getListeningDuration: function () {
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo && userInfo.userId) {
      // 获取当前日期
      const today = new Date();
      const currentYear = today.getFullYear();
      const currentMonth = today.getMonth() + 1; // JavaScript月份从0开始
      const currentDay = today.getDate();

      wx.request({
        url: `${app.globalData.apiBaseUrl}/api/v1/listening_duration`,
        method: "GET",
        data: {
          day: currentDay,
          year: currentYear,
          month: currentMonth,
          user_id: userInfo.userId,
        },
        success: (res) => {
          if (res.data && res.data.code === 0) {
            // 将今日听歌时长（分钟）转换为小时，并保留一位小数
            const todayMinutes = res.data.total_duration || 0;
            const hours = (todayMinutes / 60).toFixed(1);
            this.setData({
              listeningHours: hours,
            });
          }
        },
        fail: (err) => {
          console.error("获取今日听歌时长失败", err);
          this.setData({
            listeningHours: 0,
          });
        },
      });
    }
  },

  /**
   * 跳转到设备管理页面
   */
  navigateToDeviceManagement: function () {
    wx.navigateTo({
      url: "/pages/device/device",
    });
  },

  /**
   * 跳转到账号安全页面
   */
  navigateToAccountSecurity: function () {
    wx.navigateTo({
      url: "/pages/profile/security",
    });
  },

  /**
   * 跳转到通知设置页面
   */
  navigateToNotificationSettings: function () {
    wx.navigateTo({
      url: "/pages/profile/notification",
    });
  },

  /**
   * 编辑资料
   */
  editProfile: function () {
    const that = this;
    wx.showModal({
      title: "修改昵称",
      editable: true,
      placeholderText: "请输入新昵称",
      content: this.data.userInfo.nickname || "",
      success(res) {
        if (res.confirm) {
          // 用户点击确定，获取输入的昵称
          const newNickname = res.content;
          if (newNickname.trim() === "") {
            wx.showToast({
              title: "昵称不能为空",
              icon: "none",
            });
            return;
          }

          // 获取用户ID
          const userInfo = wx.getStorageSync("userInfo");
          const userId = userInfo.userId || that.data.userInfo.id;

          if (!userId) {
            wx.showToast({
              title: "用户信息不完整，请重新登录",
              icon: "none",
            });
            return;
          }

          // 调用接口更新昵称
          wx.request({
            url: `https://smartsound.top/api/v1/update_nickname`,
            method: "POST",
            data: {
              user_id: userId,
              nickname: newNickname,
            },
            success: (res) => {
              if (res.data && res.data.code === 0) {
                // 更新成功
                wx.showToast({
                  title: "昵称更新成功",
                  icon: "success",
                });

                // 更新本地存储
                userInfo.nickname = newNickname;
                wx.setStorageSync("userInfo", userInfo);

                // 更新页面显示
                that.setData({
                  "userInfo.nickname": newNickname,
                });
              } else {
                wx.showToast({
                  title: res.data.message || "更新失败",
                  icon: "none",
                });
              }
            },
            fail: (err) => {
              console.error("更新昵称失败", err);
              wx.showToast({
                title: "网络错误，请稍后再试",
                icon: "none",
              });
            },
          });
        }
      },
    });
  },

  /**
   * 跳转到用户画像页面
   */
  navigateToUserProfile: function () {
    wx.navigateTo({
      url: "/pages/profile/user-profile",
    });
  },

  /**
   * 跳转到使用帮助页面
   */
  navigateToHelp: function () {
    wx.navigateTo({
      url: "/pages/help/help",
    });
  },

  /**
   * 跳转到意见反馈页面
   */
  navigateToFeedback: function () {
    wx.navigateTo({
      url: "/pages/feedback/feedback",
    });
  },

  /**
   * 跳转到设置页面
   */
  navigateToSettings: function () {
    wx.navigateTo({
      url: "/pages/settings/settings",
    });
  },

  /**
   * 跳转到关于我们页面
   */
  navigateToAbout: function () {
    wx.navigateTo({
      url: "/pages/about/about",
    });
  },

  /**
   * 退出登录
   */
  logout: function () {
    // 清除本地存储的用户信息和token
    wx.removeStorageSync("userInfo");
    wx.removeStorageSync("token");
    wx.removeStorageSync("access_token");

    // 跳转到登录页面
    wx.reLaunch({
      url: "/pages/login/login",
    });
  },
});
